package com.test.springboot.alicloudsms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.test.springboot.alicloudsms.service.AlicloudSmsService;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/8/11 2:16
 * @package com.test.springboot.alicloudsms.service
 * @description 文件说明
 */
@Service
public class AlicloudSmsServiceImpl implements AlicloudSmsService {

    @Override
    public boolean sendSms(String phoneNumber, String templateCode, Map<String, Object> codes) {
        // 连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5t5wK8ammdKLP9DtYJXS", "YfBbnzS0aB81MAfhisliQyb7qwVoJw");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 自定义的参数（手机号，验证码，签名，模板）
        // request.putQueryParameter("RegionId","cn-hangzhou");
        // 手机号码
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        // 签名
        request.putQueryParameter("SignName", "连云港望潮信息科技");
        // 模板
        request.putQueryParameter("TemplateCode", templateCode);

        // 设置模板内参数
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(codes));

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
